var count = 0;
var files = '';
var lastTime = 0;
        
function prepare(response) {
    var d = new Date();
    count++;
    d.setTime(response.time*1000);
    var mytime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
    var string = '<div class="shoutbox-list" id="list-'+count+'">'
    + '<span class="shoutbox-list-time">'+mytime+'</span>'
    + '<span class="shoutbox-list-nick">'+response.nickname+':</span>'
    + '<span class="shoutbox-list-message">'+response.message+'</span>'
    +'</div>';
          
    return string;
}
        
function success(response, status)  { 
    if(status == 'success') {
        lastTime = response.time;
        $('#daddy-shoutbox-response').html('<img src="'+files+'images/accept.png" />');
        $('#daddy-shoutbox-list').prepend(prepare(response));
//        $('input[@name=message]').attr('value', '').focus();
        $('input[name=\'message\']').attr('value', '').focus();
        $('#list-'+count).fadeIn('slow');
        timeoutID = setTimeout(refresh, 3000);
    }
}
        
function validate(formData, jqForm, options) {
    for (var i=0; i < formData.length; i++) { 
        if (!formData[i].value) {
            alert('Please fill in all the fields'); 
            $('input[@name='+formData[i].name+']').css('background', 'red');
            return false; 
        } 
    } 
    $('#daddy-shoutbox-response').html('<img src="'+files+'images/loader.gif" />');
    clearTimeout(timeoutID);
}

function refresh() {
    $.getJSON(files+"daddy-shoutbox.php?action=view&time="+lastTime, function(json) {
        if(json.length) {
            for(i=0; i < json.length; i++) {
                $('#daddy-shoutbox-list').prepend(prepare(json[i]));
                $('#list-' + count).fadeIn('slow');
            }
            var j = i-1;
            lastTime = json[j].time;
        }
    //alert(lastTime);
    });
    timeoutID = setTimeout(refresh, 3000);
}
        
// wait for the DOM to be loaded 
$(document).ready(function() { 
    var options = { 
        dataType:       'json',
        beforeSubmit:   validate,
        success:        success
    }; 
    $('#daddy-shoutbox-form').ajaxForm(options);
    timeoutID = setTimeout(refresh, 100);
});
